# encoding: utf-8

class UsersController < ApplicationController

  skip_before_filter :check
  def signup
	@user = User.new(params[:user])
	if request.post?  
      if @user.save
        session[:user] = User.authenticate(@user.name, @user.password)
        cart = Cart.create(params[:cart])
        @user.cart = cart
        #session[:cart] = Cart.find_by_email(session[:user].email)
        flash[:notice] = "Signup successful"
        redirect_to_stored          
      else
        flash[:notice] = "Signup unsuccessful"
      end
    end
  end

  def login
    if request.post?
      if session[:user] = User.authenticate(params[:user][:name], params[:user][:password])
        flash[:notice]  = "Login successful"
        #session[:cart] = Cart.find_by_email(session[:user].email)
        redirect_to_stored
      else
        flash[:notice] = "Login unsuccessful"
      end
    end
  end

  def logout
    session[:user] = nil
    #session[:cart] = nil
    flash[:notice] = 'Logged out'
    redirect_to_stored
  end

  def forgot_password
    if request.post?
      u= User.find_by_email(params[:user][:email])
      if u and u.send_new_password
        flash[:notice]  = "Mật khẩu mới đã được gửi tới email của bạn."
        #Notifications.welcome_email(u).deliver
        redirect_to :action=>'login'
      else
        flash[:notice]  = "Không thể gửi được mật khẩu mới."
      end
    end
  end

  def edit
    @user=session[:user]
    if request.post?
      @user.update_attributes(params[:user])
      if @user.save
        flash[:notice]="Password Changed"
      end
    end
  end

  def change_password
    @user=session[:user]
    if request.post?
      @user.update_attributes(:password=>params[:user][:password], :password_confirmation => 
        params[:user][:password_confirmation])
      if @user.save
        flash[:notice]="Password Changed"
      end
    end
  end
end
